const cron = require("node-cron");
const moment = require("moment");
const { Op } = require("sequelize");
const { logger, logInfo, logWarn } = require("../logger/index");
const whiteList = ["/admin/captcha", "/admin/sign_in"];
const { VisitLog } = require("../models");
const { userInfo } = require("../utils/userInfo");
async function whiteFlagKey(key) {
  return whiteList.includes(key);
}
async function loggerFun(req, res, message, data = {}, code = 200) {
  // 白名单过滤

  try {
    const { baseUrl, method, body, query, params } = req;
    const { token, originname } = req.headers;
    const whiteFlag = await whiteFlagKey(baseUrl);
    let user = {};
    if (token) {
      const { user: userValue } = await userInfo(req);

      user = userValue || {};
    }

    if (data.hasOwnProperty("list")) {
      delete data.list;
    }
    logInfo(message, {
      status: true,
      route: baseUrl,
      method: method,
      params,
      body: JSON.stringify(body),
      originName: originname,
      user: whiteFlag ? "/" : user.username,
      query: JSON.stringify(query),
      userAgent: req.headers["user-agent"],
      data: whiteFlag ? {} : data,
    });
  } catch (error) {
    console.log(error);
  }
}
async function errorFun(req, error) {
  const { baseUrl, method, body, query, params } = req;
  const { token, originname } = req.headers;
  const whiteFlag = await whiteFlagKey(baseUrl);
  let user = {};
  if (token) {
    const { user: userValue } = await userInfo(req);

    user = userValue || {};
  }
  logWarn(`请求失败: ${error.name}`, {
    status: false,
    message: `请求失败: ${error.name}`,
    route: baseUrl,
    method: method,
    body: JSON.stringify(body),
    originName: originname,
    user: whiteFlag ? "/" : user.username,
    query: JSON.stringify(query),
    params,
    userAgent: req.headers["user-agent"],
  });
}
// 定时清理数据库
async function clearVisitLog() {
  console.log("清除日志");
  // 每天凌晨10点执行任务
  cron.schedule("0 10 * * *", async () => {
    try {
      const now = moment(new Date()).utcOffset(8).format("YYYY-MM-DD HH:mm:ss");
      // 每次都清除一个月前的数据
      const monthAgo = moment(now).subtract(1, "months").toDate();

      await VisitLog.destroy({
        where: {
          timestamp: {
            [Op.lt]: monthAgo,
          },
        },
      });
    } catch (error) {
      console.error("Error clearing logs:", error);
    }
  });
}

module.exports = {
  loggerFun,
  errorFun,
  clearVisitLog,
};
